﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;

namespace GoViewServer.Core
{
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services, IConfiguration configuration )
        {
            var type = configuration["ConnectionConfigs:DbType"].ToLower();
            var DbType = SqlSugar.DbType.MySql;
            if (type == "sqlserver")
            {
                DbType = SqlSugar.DbType.SqlServer;
            }
            else if(type=="sqlite"){
                DbType = SqlSugar.DbType.Sqlite;
            }
            else if (type == "questdb")
            {
                DbType = SqlSugar.DbType.QuestDB;
            }
            else if (type == "mysql")
            {
                DbType = SqlSugar.DbType.MySql;
            }
            var configConnection = new ConnectionConfig()
            {
                DbType = DbType,
                ConnectionString = configuration["ConnectionConfigs:ConnectionString"],
                IsAutoCloseConnection = true,
                InitKeyType=InitKeyType.Attribute
            };

            SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
                db =>
                {
                //单例参数配置，所有上下文生效
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                    //Console.WriteLine(sql);//输出sql
                    };
                });
            services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
        }
    }
}
